package com.tssup.fesco.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.*;

/**
 * Created by neron.liu on 9/6/16.
 */
public final class ConvertUtils {

    private static final Logger logger = LoggerFactory.getLogger(ConvertUtils.class);

    /**
     * 解析二部HTTP POST中的数据
     */
    private static final String POST_BODY_REGEX = "(\\w{1,})=([_0-9a-zA-Z\\:\\/\\.\\-\\u4e00-\\u9fa5]{0,})";

    /**
     * java.util.regex.Pattern 是线程安全的
     */
    private static final Pattern postBodyPattern = compile(POST_BODY_REGEX);

    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static <T> T convertTo(String postBody, Class<T> beanType) {
        Map<String, Object> found = new HashMap<>();

        Matcher matcher = postBodyPattern.matcher(postBody);
        while (matcher.find()) {
            String key = matcher.group(1);
            Object val = matcher.group(2);
            logger.debug("Found {} and {}", key, val);
            found.put(key, val);
        }

        if (found.size() < 1) {
            logger.warn("Nothing matched '{}', body={}", POST_BODY_REGEX, postBody);
            return null;
        }

        T bean = objectMapper.convertValue(found, beanType);
        if (logger.isDebugEnabled()) {
            try {
                logger.debug("Converted {}[{}]", beanType.getClass().getName(), objectMapper.writeValueAsString(bean));
            } catch (JsonProcessingException e) {
                // Ignore
            }
        }
        return bean;
    }

}
